package com.itcam;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * @author : Cammy.Wu
 * Description : 
 */

//@WebServlet("/demo")
public class HttpServletDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建内存图象
        BufferedImage bufferedImage = new BufferedImage(100, 30, BufferedImage.TYPE_INT_BGR);
        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 100, 30);

        // 生成随机验证码
        String code = String.valueOf(new Random().nextInt(8999) + 1000);
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font("Arial", Font.BOLD, 20));
        graphics.drawString(code, 20, 20);

        // 设置响应头
        resp.setContentType("image/jpeg");
        resp.setHeader("Pragma", "no-cache");

        // 输出图像流
        ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
